const http = require('http')
const qs = require('querystring')
const { executeSQL } = require('./database/database')

const server = http.createServer((req, res) => {
    res.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:5500')
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,DELETE")
    res.setHeader("Access-Control-Allow-Headers", "Content-Type,token")
    res.setHeader('Access-Control-Allow-Credentials', 'true');
    res.setHeader('Content-Type', 'application/json;charset=utf-8;')

    const method = req.method
    const url = req.url
    const path = url.split('?')[0]
    const query = qs.parse(url.split('?')[1])

    if(path == '/login') {
        
        let data = ''
        req.on('data', (chunk) => {
            data += chunk.toString()
        })
        req.on('end', () => {
           
            console.log('data',data)
            // const sql = `SELECT * FROM users WHERE username = \'沈俞佑\'`
            const sql = `SELECT * FROM users WHERE username='`+ JSON.parse(data).username +`' AND \`password\` = '`+JSON.parse(data).password+`'`  
            console.log(sql)
            executeSQL(sql).then(ans => {
                if(JSON.parse(data).username == ans[0].username) {
                    res.end(JSON.stringify(ans[0].id))
                } else {
                    res.end('-1')
                }
            }).catch((err) => {
                console.warn(err)
                res.end("-1")
            })
            // return JSON.stringify(data)
        })
    } else if(path == '/register') {
        let data = ''
        req.on('data', chunk => {
            data += chunk.toString()
        })
        
        req.on('end', () => {
            const username = JSON.parse(data).username
            const password = JSON.parse(data).password
            const phonenum = JSON.parse(data).phonenum
            const sql = `INSERT INTO users(username, \`password\`, phonenum)  VALUES('`+username+`','`+password+`',`+ phonenum + `)`
            console.log(sql)
            executeSQL(sql).then(ans => {
                console.log('数据添加成功')
                executeSQL(`SELECT id FROM users WHERE username = ` + username ).then(ans2 => {
                    res.end(ans2[0].id)
                }).catch(err => console.log(err))
            }).catch((err) => {
                console.warn(err)
                res.end('-1')
            })
        })
        
        
    } else if(method == 'POST' && path == '/select') {
        let data = ''
        req.on('data', chunk => {
            data += chunk.toString()
        })
        req.on('end', () => {
            const id = JSON.parse(data).id
            // const sql = `SELECT * FROM users JOIN contact ON users.id = contact.user_id WHERE users.id =` + id
            // const sql = `SELECT friend_id, username, phonenum FROM contact JOIN users ON contact.\`id\` =`+ id
            const sql = `SELECT user_id, username, phonenum FROM users JOIN contact ON contact.user_id =  users.\`id\` WHERE contact.friend_id =`+id
            executeSQL(sql).then(ans => {
                res.end(JSON.stringify(ans))

            }).catch(err => {
                console.log(err)
            })
        }) 
    } else if(path == '/delete') {
        let data = ''
        req.on('data', chunk => {
            data += chunk.toString()
        })
        req.on('end', () => {
            const delid = JSON.parse(data).deleteid
            const id = JSON.parse(data).id
            const sql = `DELETE FROM contact WHERE (user_id = `+id+` AND friend_id = `+delid+`) OR (user_id = `+delid+` AND friend_id = `+id+`) `
            console.log(sql)
            executeSQL(sql).then(ans => {
                console.log('数据添加成功')
                res.end('1')
            }).catch((err) => {
                console.warn(err)
                res.end('-1')
            })
        })
    } else if(path == '/add') {                                                                                                                                                                                                                                                                                                                          
        let data = ''
        req.on('data', chunk => {
            data += chunk.toString()
        })
        req.on('end', () => {
            const addid = JSON.parse(data).addid
            const id = JSON.parse(data).id
            const sql = `INSERT INTO contact(user_id, friend_id)  VALUES(`+id+`,`+addid+`)`
            console.log(sql)
            executeSQL(sql).then(ans => {
                console.log('数据添加成功')
                res.end('1')
            }).catch((err) => {
                console.warn(err)
                res.end('-1')
            })
        })
    } else if(path == '/change') {
        let data = ''
        req.on('data', chunk => {
            data += chunk.toString()
        })
        req.on('end', () => {
            console.log(data)
            const name = JSON.parse(data).name
            const pswd = JSON.parse(data).pswd
            const phonenum = JSON.parse(data).phonenum
            const id = JSON.parse(data).id
            const sql = `UPDATE users SET username = '`+name+`', \`password\` =`+pswd+`, phonenum = `+phonenum+` WHERE id = `+id
            executeSQL(sql).then(ans => {
                console.log('数据修改成功')
                res.end('1')
            }).catch(err => {
                res.end('-1')
            })
        })
    } else {
        res.writeHead(404, {'Content-Type':'text/plain'})
        res.write(`<h1>我敲，竟然能404</h1>`)
        res.end()
    }
})

server.listen(5678, () => {
    console.log('服务器在5678端口上开启...')
})